const {wxLogin} = require('./wxPromise')
const {GetAuth, Auth} = require('../config/index')
const {request} = require('../utils/wxRequest')
const authRequest = (params) => {
    return new Promise(async (resolve, reject) => {
        try {
          
            let login = await wxLogin()
            let formData = {}
            formData.code = login.code;
            if (params) {
                formData.nickName = params.nickName
                formData.sex = params.gender
                formData.language = params.language
                formData.city = params.city
                formData.province = params.province
                formData.country = params.country
                formData.headimgurl = params.avatarUrl
            }
            wx.request({
                url: 'http://127.0.0.1:3000/auth/wxlogin',
                method: 'post',
                data: formData,
                success(res) {
                    resolve(res)
                },
                fail(e) {
                    reject(e)
                }
            })
        } catch (e) {
            reject(e)
        }
    })
}
const auth = async (formData) => {
    return new Promise(async (resolve, reject) => {
        try {
            let {data} = await authRequest(formData)
            wx.setStorageSync('state', {
                expiredDate: Date.now() + 60 * 60 * 1000/*缓存一个小时*/,
                user: data
            })
            resolve(data)
        } catch (e) {
            reject(e)
        }
    })
}
const getAuth = async () => {
    return new Promise(async (resolve, reject) => {
        try {
            let {code} = await wxLogin()
            wx.request({
                url: 'http://127.0.0.1:3000/auth/wxlogin',
                method: 'post',
                data: {code},
                success(res) {
                  let data= res.data;
                  if(data.token){
                    wx.setStorageSync('state', {
                      expiredDate: Date.now() + 60 * 60 * 1000/*缓存一个小时*/,
                      user: data
                    })
                  }
                  console.log(res)
                    resolve(res)
                },
                fail(e) {
                    reject(e)
                }
            })
        } catch (e) {
            reject(e)
        }
    })
}
module.exports = {
    auth,
    getAuth
}
